import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';
import { Row, Col, Button, Card } from 'antd';

import styled from '@emotion/styled';
import { Global, css } from '@emotion/core';
import { colors } from '@atlaskit/theme';
import { getLocalStorageInfo } from '@/utils/localStorageInfo';

import {
  getTaskPageList,
  createTask,
  publishTask,
  auditTask,
  getTaskDetails,
  getAccountCategoryByCustomerNo,
} from './service';

// fake data generator 获取任务数据
const getItems = (count, offset = 0) =>
  Array.from({ length: count }, (v, k) => k).map((k) => ({
    id: `item-${k + offset}-${new Date().getTime()}`,
    content: `item ${k + offset}`,
  }));

const getTaskItems = (tasks, count) =>
  tasks.map((task) => ({
    id: task.serialNo,
    ccy: task.ccy,
    createTime: task.createTime,
    taskName: task.taskName,
    status: task.status,
    content: task.taskName,
    description: task.description,
    incentiveAmount: task.incentiveAmount,
  }));

const reorder = (list, startIndex, endIndex) => {
  const result = Array.from(list);
  const [removed] = result.splice(startIndex, 1);
  result.splice(endIndex, 0, removed);

  return result;
};

/**
 * Moves an item from one list to another list.
 */
const move = (source, destination, droppableSource, droppableDestination) => {
  const sourceClone = Array.from(source);
  const destClone = Array.from(destination);
  const [removed] = sourceClone.splice(droppableSource.index, 1);

  destClone.splice(droppableDestination.index, 0, removed);

  const result = {};
  result[droppableSource.droppableId] = sourceClone;
  result[droppableDestination.droppableId] = destClone;

  return result;
};

const getItemStyle = (isDragging, draggableStyle) => ({
  // some basic styles to make the items look a bit nicer
  userSelect: 'none',
  margin: `0 5px ${grid}px 5px`,

  // change background colour if dragging
  background: isDragging ? 'lightgreen' : '#ffffff',

  // styles we need to apply on draggables
  ...draggableStyle,
});
const getListStyle = (isDraggingOver) => ({
  background: isDraggingOver ? 'lightblue' : 'lightgrey',
  padding: grid,
  width: 250,
});

const grid = 8;

const borderRadius = 2;

const Container = styled.div`
  margin: ${grid}px;
  display: flex;
  flex-direction: column;
  background-color: '#dfe1e6';
  background-color: rgb(208 211 217);
`;

const Header = styled.div`
  display: flex;
  align-items: center;
  justify-content: center;
  border-top-left-radius: ${borderRadius}px;
  border-top-right-radius: ${borderRadius}px;
  background-color: ${({ isDragging }) =>
    isDragging ? colors.G50 : colors.N30};
  transition: background-color 0.2s ease;

  &:hover {
    background-color: ${colors.G50};
  }
`;

// $ExpectError - not sure why
const Title = styled.h4`
  padding: ${grid}px;
  transition: background-color ease 0.2s;
  flex-grow: 1;
  user-select: none;
  position: relative;

  &:focus {
    outline: 2px solid ${colors.P100};
    outline-offset: 2px;
  }
`;

export default () => {
  // 任务状态
  const [state, setState] = useState([]);

  let customerInfo = getLocalStorageInfo('customerInfo');

  const getTaskList = async () => {
    const pagination = { pageSize: 10, current: 1 };

    let res = await getTaskPageList({
      ...pagination,
    });

    setState([
      // getTaskItems(res.data, res.data.length),
    ]);
  };

  useEffect(() => {
    getTaskList();
  }, []);

  const [taskTitle, setTaskTitle] = useState([
    '待处理',
    '处理中',
    '待验收',
    '已完成',
  ]);

  function onDragEnd(result) {
    const { source, destination } = result;

    // dropped outside the list
    if (!destination) {
      return;
    }
    const sInd = +source.droppableId;
    const dInd = +destination.droppableId;

    if (sInd === dInd) {
      const items = reorder(state[sInd], source.index, destination.index);
      const newState = [...state];
      newState[sInd] = items;
      setState(newState);
    } else {
      const result = move(state[sInd], state[dInd], source, destination);
      const newState = [...state];
      newState[sInd] = result[sInd];
      newState[dInd] = result[dInd];

      setState(newState.filter((group) => group.length));
    }
  }

  return (
    <Card>
      <div
        style={{
          width: '100%',
          minHeight: '500px',
        }}
      >
        <Row>
          <DragDropContext onDragEnd={onDragEnd}>
            {state.map((el, ind) => (
              <Droppable key={ind} droppableId={`${ind}`}>
                {(provided, snapshot) => (
                  <Col className="gutter-row" span={6} style={{}}>
                    <Container
                      ref={provided.innerRef}
                      {...provided.droppableProps}
                    >
                      <Header isDragging={snapshot.isDragging}>
                        <Title
                          isDragging={snapshot.isDragging}
                          {...provided.dragHandleProps}
                          aria-label={`quote list`}
                        >
                          {taskTitle[ind]}
                        </Title>
                      </Header>

                      {el.map((item, index) => (
                        <Draggable
                          key={item.id}
                          draggableId={item.id}
                          index={index}
                        >
                          {(provided, snapshot) => (
                            <Card
                              size="small"
                              title={item.taskName}
                              extra={<a href="#">详情</a>}
                              ref={provided.innerRef}
                              {...provided.draggableProps}
                              {...provided.dragHandleProps}
                              style={getItemStyle(
                                snapshot.isDragging,
                                provided.draggableProps.style,
                              )}
                            >
                              <Row>
                                <Col span={12}>{item.description}</Col>
                                <Col span={12}>{item.status}</Col>
                              </Row>
                              <Row
                                style={{
                                  borderTop: '1px solid',
                                }}
                              >
                                <Col
                                  span={10}
                                >{`${item.incentiveAmount} ${item.ccy}`}</Col>
                                <Col span={14}>{item.createTime}</Col>
                              </Row>
                            </Card>
                          )}
                        </Draggable>
                      ))}

                      {provided.placeholder}
                    </Container>
                  </Col>
                )}
              </Droppable>
            ))}
          </DragDropContext>
        </Row>
      </div>
    </Card>
  );
};
